/*
 *  @author zhangqiang
 *  @data 2017/07/26
 *   添加地址
 * */

import React, { Component } from 'react';
import {Toast,Picker, List} from 'antd-mobile';
import { createForm } from 'rc-form';
import { Title } from '../../components/common'
import style from './index.scss'
import {connect} from 'react-redux';
import {InputItem} from '../../components/home'
import NotExpression from '../../utils/expression'
import {getAddAddressEdit} from '../../actions/addAddressEditActions'
import {
	address,
	setAddAddress
} from '../../actions/addAddressActions';
import {
	allAddressData
} from '../../components/common/addressData'
import common from '../../utils/common'
import '../../../styles/addAddress.scss';

class addressEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
	        name: '', //姓名 自由类型
	        nameImg: false,
	        nameWidth: '.3rem', // 姓名的默认宽度
	        nameNoBlur: true, //点击删除按钮不执行失去焦点验证

	        phone: '', //姓名 自由类型
	        phoneImg: false,
	        phoneWidth: '.3rem', // 姓名的默认宽度
	        phoneNoBlur: true, //点击删除按钮不执行失去焦点验证

	        district: '', //省市区拼接
	        details: '', //详细地址

	        addressData: '', //省市区接口数据

	        provinceName: '',  //省
	        provinceId:'',
	        cityName: '',  //市
	        cityId:'',
	        countyName: '',  //区
	        countyId: ''
        }
	    this.addressId = this.props.params.addressId;
    }

    componentDidMount() {
	    common.setViewTitle('编辑地址');

	    let getData = {
		    id: this.addressId
	    };
	    getAddAddressEdit(getData,(res)=>{
		    this.setState({
			    name: res.contactName,
			    phone: res.cellNum,
			    district: res.provinceName+res.cityName+res.countyName,
			    details: res.street,
			    provinceName: res.provinceName,
			    provinceId: res.provinceId,
			    cityName: res.cityName,
			    cityId: res.cityId,
			    countyName: res.countyName,
			    countyId: res.countyId,
			    nameImg: 'correct',  //编辑地址都验证过了
			    nameWidth: '.4rem',
			    phoneImg: 'correct',
			    phoneWidth: '.4rem',
			    detailsImg: 'correct',
			    detailsWidth: '.4rem'
		    })
	    })
	    document.querySelector('.am-list-extra').style.color = '#6a6a6a';
    }

	getAllAddressData(){
		let addressData={
			provinceId: 440000,
			bizType: 0
		};
		Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
		Toast.loading("", 30, () => Toast.info("网络错误", 2));
		address(addressData,(res)=>{
			this.setState({
				addressData: res
			})
		})
	}

	/*
		*   省市区
		* */
	getRegion(e){
		document.querySelector('.am-list-extra').style.color='#6a6a6a';
	}

	subMit(){
		this.props.form.validateFields((error, value) => {
			let telNum = this.state.phone.replace(/\s+/g, ""),
				reg = /^0?1[3|4|5|7丨8][0-9]\d{8}$/,
				// reg_name = /^[a-zA-Z\u4e00-\u9fa5\s]{1,20}$/,
				reg_name = /^[\u4e00-\u9fa5]{2,12}$/,
				reg_details = /^[\u4e00-\u9fa5]{5,100}$/;
			// if (!this.state.name && !this.state.phone && !this.state.district && !value.focus) {
			// 	Toast.info('请填写资料', 1);
			// 	return false;
			// } else {

				if (this.state.name == '' || !this.state.name || this.state.name.replace(/(^\s*)|(\s*$)/g, "") == "") {
					Toast.info('请输入正确的收件人姓名', 1);
					return false;
				} else if (!reg_name.test(this.state.name)) {
					Toast.info('姓名格式错误', 1)
					return false;
				} else if (NotExpression.isEmojiCharacter(this.state.name.toString())) {
					Toast.info('姓名不能包含表情', 1);
					return false;
				} else if (this.state.phone == '' || !this.state.phone) {
					Toast.info('请输入正确的联系电话', 1);
					return false;
				} else if (!reg.test(telNum)) {
					Toast.info('手机格式错误', 1)
					return false;
				} else if (!this.state.provinceName || !this.state.cityName) {
					Toast.info('请选择省市区（县）', 1);
					return false;
				} else if (this.state.details == '' || !this.state.details|| this.state.details.replace(/(^\s*)|(\s*$)/g, "") == "") {
					Toast.info('请输入详细地址', 1);
					return false;
				} else if (this.state.details.toString().length < 5) {
					Toast.info('详细地址长度应不少于5位', 1);
					return false;
				}
				// else if(!reg_details.test(this.state.details)){
				// 	Toast.info('详细地址格式错误', 1);
				// 	return false;
				// }
			//}

			let provinceName = value.district ? value.district[0].split(',')[0] : this.state.provinceName, //省份
						cityName = value.district ? value.district[1].split(',')[0] : this.state.cityName, //城市
						countyName= value.district ? value.district[2].split(',')[0] : this.state.countyName,//所在区
						areaCode_s,
						areaName_s;

			if (!value.district) {  //中山 ，和东莞没有区，和第三级列表
				areaCode_s = this.state.countyId;
				areaName_s = this.state.countyName;
			} else if (value.district.length == 3) {
				areaCode_s = value.district[2].split(',')[1];
				areaName_s = value.district[2].split(',')[0];
			} else if (value.district.length == 2) {
				areaCode_s = '';
				areaName_s = '';
			}
			let cacheData = {
				contactName: this.state.name,
				cellNum : this.state.phone,
				id: this.addressId,
				provinceId: value.district ? value.district[0].split(',')[1] : this.state.provinceId, //省份code
				provinceName: provinceName, //省份
				cityId: value.district ? value.district[1].split(',')[1] : this.state.cityId,//城市code
				cityName: cityName,//城市
				countyId: areaCode_s,//所在区code
				countyName: areaName_s,//所在区
				street: this.state.details,
				fullAddr: provinceName+cityName+countyName+this.state.details
			};

			setAddAddress(cacheData,()=>{
				setTimeout(()=>{history.go(-1)},250)
			})
		});
	}

    render() {
	    const { getFieldProps } = this.props.form;
		let that = this;
	    return (
        <div className={style.addAddress}>
	        <div style={{height: '.24rem'}}></div>
	        <div>
		        <Title text='邮政速递人员将按此地址上门取件和送件，请准确、完整的填写' isLine={true}/>
		        <InputItem type="text" index='2' itemText="姓名" maxLength="12" placeHolder="收件人姓名" id="name"
				value={this.state.name} showUnderLine={true} showTagText={false} creditCodeImg={this.state.nameImg} creditWidth = {this.state.nameWidth}
					onClick={()=>{
						this.setState({
							name: '',
							nameImg: 'hideDelete',
							nameNoBlur: false
						})
						document.querySelector('#name').focus();
					}}
					onBlur={(event)=>{
						let res = event.target.value;
						this.setState({nameNoBlur: true});
						setTimeout(()=>{
							if(!this.state.nameNoBlur) return;  //点击删除按钮不执行验证
							let value = res,
								nameRule1= /^[\u4e00-\u9fa5]{2,12}$/;

							if(value == ''){
								this.setState({
									nameImg: '',
								});
							}else if(nameRule1.test(value)){
								this.setState({
									nameImg: 'correct',
									nameWidth: '.4rem'
								});
							}else {
								this.setState({
									nameWidth: '.4rem',
									nameImg: 'error'
								})
							}
						},0)
					}}
					onFocus={(e)=>{
						let value = e.target.value;
						if(value.length!=0&&value==this.state.name){
							this.setState({
								nameImg: 'showDelete',
							});
						}
					}}
					onChange={(e) => {
						let value = e.target.value;
						if(value.length>0&&value!=' '){
							this.setState({
								nameImg: 'showDelete',
								name: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}else {
							this.setState({
								nameImg: 'hideDelete',
								name: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}
					}}/>

		        <InputItem type="text" index='2' itemText="联系电话" maxLength="11" placeHolder="联系电话" id="phone"
				value={this.state.phone} showUnderLine={false} showTagText={false} creditCodeImg={this.state.phoneImg} creditWidth = {this.state.phoneWidth}
					onClick={()=>{
						this.setState({
							phone: '',
							phoneImg: 'hideDelete',
							phoneNoBlur: false
						})
						document.querySelector('#phone').focus();
					}}
					onBlur={(event)=>{
						let res = event.target.value;
						this.setState({phoneNoBlur: true});
						setTimeout(()=>{
							if(!this.state.phoneNoBlur) return;  //点击删除按钮不执行验证
							let value = res,
								phoneRule = /^0?1[3|4|5|7丨8][0-9]\d{8}$/;

							if(value == ''){
								this.setState({
									phoneImg: '',
								});
							}else if(phoneRule.test(value)){
								this.setState({
									phoneImg: 'correct',
									phoneWidth: '.4rem'
								});
							}else {
								this.setState({
									phoneWidth: '.4rem',
									phoneImg: 'error'
								})
							}
						},0)
					}}
					onFocus={(e)=>{
						let value = e.target.value;
						if(value.length!=0&&value==this.state.phone){
							this.setState({
								phoneImg: 'showDelete',
							});
						}
					}}
					onChange={(e) => {
						let value = e.target.value;
						if(value.length>0&&value!=' '){
							this.setState({
								phoneImg: 'showDelete',
								phone: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}else {
							this.setState({
								phoneImg: 'hideDelete',
								phone: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}
					}}/>
		        <div style={{height: '.24rem'}}></div>

		        <Picker extra={this.state.district.replace(null,'') || "省、市、区（县）"} data={allAddressData.value}//this.state.addressData
					format={(values) => { { return values.join(''); } }}
					title="选择地区" {...getFieldProps('district', {
			        onChange(e) {
				        that.getRegion(e)
			        },
		        }) }
		        >
			        <List.Item arrow="horizontal"></List.Item>
		        </Picker>
		        <div className="border_bottom_1" style={{position: 'relative',paddingLeft: '.3rem'}}></div>
		        <InputItem type="text" index='2' itemText="详细地址" maxLength="100" placeHolder="详细地址" id="details"
				value={this.state.details} showUnderLine={true} showTagText={false} creditCodeImg={this.state.detailsImg} creditWidth = {this.state.detailsWidth}
					onClick={()=>{
						this.setState({
							details: '',
							detailsImg: 'hideDelete',
							detailsNoBlur: false
						})
						document.querySelector('#details').focus();
					}}
					onBlur={(event)=>{
						let res = event.target.value;
						this.setState({detailsNoBlur: true});
						setTimeout(()=>{
							if(!this.state.detailsNoBlur) return;  //点击删除按钮不执行验证
							let value = res;
								// detailsRule1= /^[\u4e00-\u9fa5]{5,100}$/;

							if(value == ''){
								this.setState({
									detailsImg: '',
								});
							}
							// else if(detailsRule1.test(value)){
								//this.setState({
									//  detailsImg: 'correct',
									//detailsWidth: '.4rem'
								//  });
							// }
							else if(value.length>=5){
								this.setState({
									detailsWidth: '.4rem',
									detailsImg: 'correct'
								})
							}else {
								this.setState({
									detailsWidth: '.4rem',
									detailsImg: 'error'
								})
							}
						},0)
					}}
					onFocus={(e)=>{
						let value = e.target.value;
						if(value.length!=0&&value==this.state.details){
							this.setState({
								detailsImg: 'showDelete',
							});
						}
					}}
					onChange={(e) => {
						let value = e.target.value;
						if(value.length>0&&value!=' '){
							this.setState({
								detailsImg: 'showDelete',
								details: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}else {
							this.setState({
								detailsImg: 'hideDelete',
								details: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}
					}}/>
	        </div>

	        <div className={style.footBtn}>
				<button type="button" onClick={()=>{this.subMit()}}>保存</button>
		        <div className={style.cancel} onClick={()=>{window.history.go(-1)}}>取消</div>
	        </div>
        </div>
      );
    }
}

//使用context
addressEdit.contextTypes = {
	router: React.PropTypes.object.isRequired
};

export default createForm()(addressEdit);
